from gglib.auth import login, authenticate
from gglib.session import Session
from gglib.packet import Packet


def handle(session, packet):
    assert isinstance(session, Session)
    username = packet['username']
    password = packet['password']
    user = authenticate(session, username=username, password=password)
    if user:
        login(session, user)
        pkt = Packet(packet)
        pkt.errcode = 0
    else:
        pkt = Packet(packet)
        pkt.errcode = 1
        pkt.errmsg = "invalid username or password"
    session.route_packet(pkt)
